package util;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.util.CharsetUtil;

import data.ISerializable;

public class ChannelBufferUtil {
	public static String readString(ChannelBuffer data) {
		int len = data.readShort();
		int index = data.readerIndex();
		String str = data.toString(data.readerIndex(), len, CharsetUtil.UTF_8);
		data.readerIndex(index+len+1);
		return str;
	}
	
	public static Object readObject(ChannelBuffer data) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		String name = ChannelBufferUtil.readString(data);
		Class<?> cl = Class.forName("data."+name);
		ISerializable result = (ISerializable)cl.newInstance();
		result.unserialize(data);
		return result;
	}
	
	public static int[] readIntArray(ChannelBuffer data) {
		int size = data.readInt();
		int[] result = new int[size];
		for (int i = 0; i < size; i++) {
			result[i] = data.readInt();
		}
		return result;
	}
	
	public static String[] readStringArray(ChannelBuffer data) {
		int size = data.readInt();
		String[] result = new String[size];
		for (int i = 0; i < size; i++) {
			result[i] = readString(data);
		}
		return result;
	}
	
	public static void writeObject(ChannelBuffer buf, ISerializable data) {
		String name = data.getClass().getName();
		name = name.substring(name.lastIndexOf('.'));
		writeString(buf, name);
		data.unserialize(buf);
	}
	
	public static void writeString(ChannelBuffer buf, String str) {
		byte[] bytes = str.getBytes(CharsetUtil.UTF_8);
		buf.writeShort(bytes.length);
		buf.writeBytes(bytes);
		buf.writeByte(0);
	}
	
	public static void writeBool(ChannelBuffer buf, boolean val) {
		buf.writeByte(val?1:0);
	}
	
}
